var { sequelize } = require("../lib/db");
var common = require("../lib/common");
var option = sequelize.import("../models/option");

exports.save = function(req, res,next) {

//   sequelize.sync().then(function(){

    var param = req.query;
    param = JSON.stringify(param);

    option.findAll({where:{optionname:"siteConfig"}}).then(function(options){
        if(options.length == 0){
            ///新增
            option.create({
                optionname:"siteConfig",
                optionvalue:param
            });
            return res.json({"errcode": 0, "errmsg": "保存成功"});
        }else{
            ///修改
            var model = options[0];
            option.update({optionvalue:param},{
                where: {
                    id: model.id
                }
            }).then(function(msg){
                return res.json({"errcode": 0, "errmsg": "保存成功"});
            });
        }
    });

//   });

}

exports.get = function(req, res,next) {
    let optionname = req.params.id || '';
    // var optionname = req.query.optionname;

    option.findAll({where:{optionname:optionname}}).then(function(options){
        if(options.length === 1){
            var model = options[0];
            model.optionvalue = JSON.parse(model.optionvalue);
            return res.json(model.optionvalue);
        }else{
            return res.json({"errcode": 40001, "errmsg": "选项不存在"})
        }
    });
}

